from .models import Lesson, Signup, Course
import math
from trainUser.models import User
from Util.token import TokenUtil
import json
from django.shortcuts import HttpResponse
from Util.jsonUtil import DateEncoder
from trainUser.views import qryEmailbyDepartment
from django.forms.models import model_to_dict
from django.http import FileResponse
from django.utils.encoding import escape_uri_path
import os
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
tokenUtil = TokenUtil()


# 每页显示个数
defaultPageSize = 10

# 课程状态 1-新增，2-已发布,3-已结束，4-已取消
statusList = ["1", "2", "3", "4"]

# 签到状态 1-已签到（已报名，且签到），0-未签到(已报名)
signUpStatue = ["0", "1"]

# 签到状态 1-是自己，0-不是
isSelfList = ["0", "1"]

# 签到状态 1-已经报名，0-未报名
isSignUpList = ["0", "1"]

#邮件标志位 , 0-发送发布邮件，1-发送取消邮件
emailFlag = [0,1]

# 添加课程
def lessonCreate(request):
    body_unicode = request.body.decode()  # getting payload data into json
    body = json.loads(body_unicode)
    user_token = body["user_token"]
    response = {}
    if tokenUtil.isLogin(user_token):
        lesson = Lesson()
        lesson.lesson_title = body['lesson_title']
        lesson.content = body['content']
        if 'link_info' in body:
            lesson.link_info = body['link_info']
        if 'attachment' in body:
            lesson.attachment = body['attachment']
        if 'lesson_code' in body:
            lesson.lesson_code = body['lesson_code']
        lesson.lesson_status = statusList[0]
        if 'lesson_type' in body:
            lesson.lesson_type = body['lesson_type']
        lesson.realm_account = tokenUtil.getRealmAccount(user_token)
        lesson.start_time = body['start_time']
        lesson.end_time = body['end_time']
        lesson.address = body['address']
        if 'signIn_code' in body:
            lesson.signIn_code = body['signIn_code']
        lesson.publish_range = body['publish_range']
        lesson.save()
        response = {'error_no': "0", 'error_info': "课程添加成功"}
    else:
        response = {'error_no': "-1", 'error_info': "未登录，请登录系统！"}
    return HttpResponse(json.dumps(response), content_type="application/json")


# 修改课程
def lessonUpdate(request):
    body_unicode = request.body.decode()  # getting payload data into json
    body = json.loads(body_unicode)
    user_token = body["user_token"]
    response = {}
    if tokenUtil.isLogin(user_token):
        lesson = Lesson.objects.get(lesson_id=body['lesson_id'])
        lesson.lesson_title = body['lesson_title']
        lesson.content = body['content']
        lesson.link_info = body['link_info']
        lesson.attachment = body['attachment']
        lesson.lesson_code = body['lesson_code']
        if "lesson_status" in body:
            lesson.lesson_status = body['lesson_status']
        else:
            lesson.lesson_status = statusList[0]
        lesson.lesson_type = body['lesson_type']
        lesson.realm_account = tokenUtil.getRealmAccount(user_token)
        lesson.start_time = body['start_time']
        lesson.end_time = body['end_time']
        lesson.address = body['address']
        lesson.signIn_code = body['signIn_code']
        lesson.publish_range = body['publish_range']
        lesson.save()
        response = {'error_no': "0", 'error_info': "课程修改成功"}
    else:
        response = {'error_no': "-1", 'error_info': "未登录，请登录系统！"}
    return HttpResponse(json.dumps(response), content_type="application/json")


# 查询课程
def lessonQry(request):
    body_unicode = request.body.decode()  # getting payload data into json
    body = json.loads(body_unicode)
    user_token = body["user_token"]
    resultList = []
    response = {}
    if tokenUtil.isLogin(user_token):
        currentPage = body['current_page']
        lessonKeyWord = body['lesson_title']
        pageSize = body['page_size']

        if currentPage != None and len(currentPage) > 0:
            currentPage = int(currentPage)
            if currentPage <= 0:
                currentPage = 1
        else:
            currentPage = 1

        if pageSize != None and len(pageSize) > 0:
            pageSize = int(pageSize)
        else:
            pageSize = defaultPageSize
        if lessonKeyWord == '' or lessonKeyWord == ' ' or lessonKeyWord == None:
            allLesson = list(Lesson.objects.all().values())
        else:
            allLesson = list(Lesson.objects.filter(lesson_title__contains=lessonKeyWord).all().values())
        totalPage = int(math.ceil(len(allLesson) / pageSize))
        if totalPage == 0:
            currentPage = 0
        if currentPage > totalPage:
            currentPage = totalPage
        if len(allLesson) >= currentPage * pageSize:
            resultList = allLesson[(currentPage - 1) * pageSize:currentPage * pageSize]
        else:
            resultList = allLesson[(currentPage - 1) * pageSize:]
        realList = []
        for subList in resultList:
            realm_account = subList["realm_account"]
            # 根据域账号判断是否为自己的课程
            if tokenUtil.getRealmAccount(user_token) == realm_account:
                isSelf = isSelfList[1]
            else:
                isSelf = isSelfList[0]
            subList["isSelf"] = isSelf
            # 根据课程id判断自己是否已经报名了
            if len(Signup.objects.filter(lesson_id=subList["lesson_id"]).all()) > 0:
                isSignUp = isSignUpList[1]
            else:
                isSignUp = isSignUpList[0]
            subList["isSignUp"] = isSignUp
            # 根据域账号获取名字
            name = ""
            nameQry = list(User.objects.filter(realm_account=realm_account).all().values())
            if len(nameQry) > 0:
                name = nameQry[0]["name"]
            subList["teacher_name"] = name
            realList.append(subList)
        response = {'error_no': "0", 'error_info': "",
                    'current_page': currentPage, 'page_size': pageSize,
                    'resultList': realList}
    else:
        response = {'error_no': "-1", 'error_info': "未登录，请登录系统！", 'resultList': []}
    return HttpResponse(json.dumps(response, cls=DateEncoder), content_type="application/json")


# 删除课程
def lessonDelete(request):
    body_unicode = request.body.decode()  # getting payload data into json
    body = json.loads(body_unicode)
    user_token = body["user_token"]
    response = {}
    if tokenUtil.isLogin(user_token):
        lesson_id = body['lesson_id']
        lesson = Lesson.objects.filter(lesson_id=lesson_id)
        lesson.delete()
        response = {'error_no': "0", 'error_info': "删除成功"}
    else:
        response = {'error_no': "-1", 'error_info': "未登录，请登录系统！"}
    return HttpResponse(json.dumps(response), content_type="application/json")


# 课程报名/取消报名
def signUpLesson(request):
    body_unicode = request.body.decode()  # getting payload data into json
    body = json.loads(body_unicode)
    user_token = body["user_token"]
    response = {}
    if tokenUtil.isLogin(user_token):
        lesson_id = body['lesson_id']
        realm_account = tokenUtil.getRealmAccount(user_token)
        if len(Signup.objects.filter(realm_account=realm_account).filter(lesson_id=lesson_id).filter(
                sign_status=signUpStatue[0]).all()) == 1:
            Signup.objects.filter(realm_account=realm_account).filter(lesson_id=lesson_id).delete()
            response = {'error_no': "0", 'error_info': "取消报名成功"}
        else:
            signUp = Signup()
            signUp.lesson_id = lesson_id
            signUp.realm_account = realm_account
            signUp.sign_status = signUpStatue[0]
            signUp.save()
            response = {'error_no': "0", 'error_info': "报名成功"}
    else:
        response = {'error_no': "-1", 'error_info': "未登录，请登录系统！"}
    return HttpResponse(json.dumps(response), content_type="application/json")


# 发布/取消发布课程
def publishLesson(request):
    body_unicode = request.body.decode()  # getting payload data into json
    body = json.loads(body_unicode)
    user_token = body["user_token"]
    response = {}
    if tokenUtil.isLogin(user_token):
        lesson_id = body['lesson_id']
        lesson = list(Lesson.objects.filter(lesson_id=lesson_id).all())
        if lesson[0].lesson_status == statusList[0]:
            Lesson.objects.filter(lesson_id=lesson_id).update(lesson_status=statusList[1])
            response = {'error_no': "0", 'error_info': "课程发布成功"}
        elif lesson[0].lesson_status == statusList[1]:
            Lesson.objects.filter(lesson_id=lesson_id).update(lesson_status=statusList[0])
            response = {'error_no': "0", 'error_info': "课程取消发布成功"}
    else:
        response = {'error_no': "-1", 'error_info': "未登录，请登录系统！"}
    return HttpResponse(json.dumps(response), content_type="application/json")


# 课程结束
def finishedLesson(request):
    body_unicode = request.body.decode()  # getting payload data into json
    body = json.loads(body_unicode)
    user_token = body["user_token"]
    if tokenUtil.isLogin(user_token):
        lesson_id = body['lesson_id']
        Lesson.objects.filter(lesson_id=lesson_id).update(lesson_status=statusList[3])
        response = {'error_no': "0", 'error_info': "课程结束"}
    else:
        response = {'error_no': "-1", 'error_info': "未登录，请登录系统！"}
    return HttpResponse(json.dumps(response), content_type="application/json")


# 取消课程
def canceledLesson(request):
    body_unicode = request.body.decode()  # getting payload data into json
    body = json.loads(body_unicode)
    user_token = body["user_token"]
    if tokenUtil.isLogin(user_token):
        lesson_id = body['lesson_id']
        Lesson.objects.filter(lesson_id=lesson_id).update(lesson_status=statusList[3])
        response = {'error_no': "0", 'error_info': "课程取消成功"}
    else:
        response = {'error_no': "-1", 'error_info': "未登录，请登录系统！"}
    return HttpResponse(json.dumps(response), content_type="application/json")


# 课程设置分数
def setScoreOfLesson(request):
    body_unicode = request.body.decode()  # getting payload data into json
    body = json.loads(body_unicode)
    user_token = body["user_token"]
    if tokenUtil.isLogin(user_token):
        lesson_id = body['lesson_id']
        score = body['score']
        Lesson.objects.filter(lesson_id=lesson_id).update(score=score)
        response = {'error_no': "0", 'error_info': "课程设置分数成功"}
    else:
        response = {'error_no': "-1", 'error_info': "未登录，请登录系统！"}
    return HttpResponse(json.dumps(response), content_type="application/json")


# 课程签到
def signInLesson(request):
    body_unicode = request.body.decode()  # getting payload data into json
    body = json.loads(body_unicode)
    user_token = body["user_token"]
    if tokenUtil.isLogin(user_token):
        lesson_id = body["lesson_id"]
        realm_account = tokenUtil.getRealmAccount(user_token)
        if len(Signup.objects.filter(realm_account=realm_account).filter(lesson_id=lesson_id).filter(
                sign_status=signUpStatue[0]).all()) == 1:
            Signup.objects.get(lesson_id=lesson_id, realm_account=realm_account).update(sign_status=signUpStatue[1])
            response = {'error_no': "0", 'error_info': "签到成功"}
        elif len(Signup.objects.filter(realm_account=realm_account).filter(lesson_id=lesson_id).filter(
                sign_status=signUpStatue[1]).all()) == 1:
            response = {'error_no': "0", 'error_info': "已经签到过，无法重复签到"}
        else:
            response = {'error_no': "0", 'error_info': "未报名，无法签到"}
    else:
        response = {'error_no': "-1", 'error_info': "未登录，请登录系统！"}
    return HttpResponse(json.dumps(response), content_type="application/json")


# 查询自己的课程
def selfLesson(request):
    body_unicode = request.body.decode()  # getting payload data into json
    body = json.loads(body_unicode)
    user_token = body["user_token"]
    if tokenUtil.isLogin(user_token):
        realm_account = tokenUtil.getRealmAccount(user_token)
        resultList = list(Lesson.objects.filter(realm_account=realm_account).all().values())
        for result in resultList:
            result["teacher_name"] = User.objects.get(realm_account=result["realm_account"]).name
        response = {'error_no': "0", 'error_info': "查询成功", "resultList": resultList}
    else:
        response = {'error_no': "-1", 'error_info': "未登录，请登录系统！", "resultList": []}
    return HttpResponse(json.dumps(response, cls=DateEncoder), content_type="application/json")


# 查询自己已报名的课程
def selfSignUpLesson(request):
    body_unicode = request.body.decode()  # getting payload data into json
    body = json.loads(body_unicode)
    user_token = body["user_token"]
    resultList = []
    if tokenUtil.isLogin(user_token):
        realm_account = tokenUtil.getRealmAccount(user_token)
        lessonList = Signup.objects.filter(realm_account=realm_account).values("lesson_id").all()
        if len(lessonList) > 0:
            for subId in lessonList:
                real_id = subId["lesson_id"]
                # 根据域账号获取名字
                lesson = Lesson.objects.get(lesson_id=real_id)
                teacher_id = lesson.realm_account
                teacher_name = User.objects.get(realm_account=teacher_id).name
                result = model_to_dict(lesson)
                result["teacher_name"] = teacher_name
                resultList.append(result)
            response = {'error_no': "0", 'error_info': "查询成功", "resultList": resultList}
        else:
            response = {'error_no': "0", 'error_info': "查询成功", "resultList": resultList}
    else:
        response = {'error_no': "-1", 'error_info': "未登录，请登录系统！", "resultList": resultList}
    return HttpResponse(json.dumps(response, cls=DateEncoder), content_type="application/json")


# 获取提示邮件的内容
def emailDetail(request):
    body_unicode = request.body.decode()  # getting payload data into json
    body = json.loads(body_unicode)
    user_token = body["user_token"]
    if tokenUtil.isLogin(user_token):
        lesson_id = body["lesson_id"]
        pLesson = list(Lesson.objects.filter(lesson_id=lesson_id).all().values())
        response = {'error_no': "0", 'error_info': "",
                    'emailStr': qryEmailbyDepartment(pLesson[0]['publish_range']),
                    'lesson_title': pLesson[0]['lesson_title'],
                    'content': pLesson[0]['content'],
                    'lesson_type': pLesson[0]['lesson_type'],
                    'start_time': pLesson[0]['start_time'],
                    'end_time': pLesson[0]['end_time'],
                    'address': pLesson[0]['address'],
                    'publish_range': pLesson[0]['publish_range']
                    }
    else:
        response = {'error_no': "-1", 'error_info': "未登录，请登录系统！", "resultList": []}
    return HttpResponse(json.dumps(response, cls=DateEncoder), content_type="application/json")


# 课程详情
def lessonDetail(request):
    body_unicode = request.body.decode()  # getting payload data into json
    body = json.loads(body_unicode)
    user_token = body.get("user_token", None)
    if TokenUtil().isLogin(user_token):
        lesson_id = body.get("lesson_id", None)
        lesson = Lesson.objects.get(lesson_id=lesson_id)
        result = model_to_dict(lesson)
        result["teacher_name"] = User.objects.get(realm_account=result["realm_account"]).name
        cour = Course.objects.filter(lesson_id=lesson_id).all().values()
        attachments = map(lambda x: {"attachment_id": x["id"], "attachment_name": os.path.basename(x["path"])},
                          cour)
        result["attachments"] = list(attachments)
        response = {'error_no': "0", 'error_info': "查询成功", "result": result}
    else:
        response = {'error_no': "-1", 'error_info': "未登录，请登录系统！", "result": None}
    return HttpResponse(json.dumps(response, cls=DateEncoder), content_type="application/json")


# 上传附件
def uploadAttachment(request):
    user_token = request.POST.get("user_token", None)
    lesson_id = request.POST.get("lesson_id", None)
    if TokenUtil().isLogin(user_token):
        try:
            real_account = TokenUtil().getRealmAccount(token=user_token)
            obj = request.FILES.get('file')
            relat_path = 'upload\{}\{}'.format(real_account, lesson_id)
            path = os.path.join(os.getcwd(), relat_path)
            if not os.path.exists(path):
                os.makedirs(path)
            file_path = os.path.join(path, obj.name)
            with open(file_path, 'wb+') as f:
                for chunk in obj.chunks():
                    f.write(chunk)
            _course = Course()
            _course.lesson_id = lesson_id
            _course.realm_account = real_account
            _course.path = os.path.join(relat_path, obj.name)
            _course.save()
            response = {'error_no': "0", 'error_info': "上传成功"}
        except Exception as e:
            response = {'error_no': "-1", 'error_info': "{}".format(e)}
    else:
        response = {'error_no': "-1", 'error_info': "未登录，请登录系统！", "result": None}
    return HttpResponse(json.dumps(response, cls=DateEncoder), content_type="application/json")



# 下载附件
def course(request):
    body = json.loads(request.body.decode())
    user_token = body.get("user_token", None)
    if TokenUtil().isLogin(user_token):
        try:
            attachment_id = body.get("attachment_id", None)
            relat_path = Course.objects.get(id=attachment_id).path
            file_path = os.path.join(os.getcwd(), relat_path)
            f=open(file_path, 'rb')
            response = FileResponse(f)
            response['Content-Type'] = 'application/octet-stream'
            response['Content-Disposition'] = "attachment; filename={}".format(
                escape_uri_path(os.path.basename(relat_path)))

#             response['Content-Disposition'] = 'attachment;filename="{}"'.format(os.path.basename(relat_path).encode("utf8").decode('ISO-8859-1')
# )
#             response['filename'] = '{}'.format(os.path.basename(relat_path).encode("utf8").decode('ISO-8859-1')
# )
            # print('{}'.format(os.path.basename(relat_path)))
            # print('{}'.format(os.path.basename(relat_path)).encode("utf8"))

            # 想在客户端app中允许获取自定义的header信息，需要在服务器端header中添加Access-Control-Expose-Headers：
            response['Access-Control-Expose-Headers']='Content-Disposition'
            return response
        except Exception as e:
            response = {'error_no': "-1", 'error_info': "{}".format(e)}
    else:
        response = {'error_no': "-1", 'error_info': "参数缺失"}
    return HttpResponse(json.dumps(response, cls=DateEncoder), content_type="application/json")


# 删除附件
def delete_course(request):
    body = json.loads(request.body.decode())
    user_token = body.get("user_token", None)
    if TokenUtil().isLogin(user_token):
        try:
            attachment_id = body.get("attachment_id", None)
            relat_path = Course.objects.get(id=attachment_id).path
            file_path = os.path.join(os.getcwd(), relat_path)
            Course.objects.get(id=attachment_id).delete()
            os.remove(file_path)
            response = {'error_no': "0", 'error_info': "删除成功"}
        except Exception as e:
            response = {'error_no': "-1", 'error_info': "{}".format(e)}
    else:
        response = {'error_no': "-1", 'error_info': "参数缺失"}
    return HttpResponse(json.dumps(response, cls=DateEncoder), content_type="application/json")


# 发送邮件
def sendEmail(request):
    body = json.loads(request.body.decode())
    user_token = body.get("user_token", None)
    if TokenUtil().isLogin(user_token):
        try:
            lesson_id = body["lesson_id"]
            flag = body["flag"]
            pLesson = list(Lesson.objects.filter(lesson_id=lesson_id).all().values())
            fromEmail = settings.DEFAULT_FROM_EMAIL
            if flag == emailFlag[0]:
                # 发布邮件
                subject = "课程" + pLesson[0]['lesson_title'] + "已经发布可以进行报名"
            elif flag == emailFlag[1]:
                # 取消发布邮件
                subject = "非常抱歉，课程" + pLesson[0]['lesson_title'] + "已经被取消"
            else:
                subject = ""
            if len(subject) > 0:
                # 获得讲师名称
                realm_account = pLesson[0]['realm_account']
                name = list(User.objects.filter(realm_account=realm_account).all().values())[0]['name']
                content = "<p><strong>讲师为：</strong></p><p>" + name + "</p>" + \
                          "<p><strong>课程内容为：</strong></p><p>" + pLesson[0]['content'] + "</p>" + \
                          "<p><strong>课程地址为：</strong></p><p>" + pLesson[0]['address'] + "</p>" + \
                          "<p><strong>课程时间为：</strong></p><p>" + \
                          pLesson[0]['start_time'].strftime('%Y-%m-%d %H:%M:%S') + "---" \
                          + pLesson[0]['end_time'].strftime('%Y-%m-%d %H:%M:%S') + "</p>"
                toEmail = qryEmailbyDepartment(pLesson[0]['publish_range']).split(';')
                # 获得邮箱列表
                realToEmail = []
                for suToEmail in toEmail:
                    realToEmail.append(suToEmail)
                msg = EmailMultiAlternatives(subject, content, fromEmail, realToEmail)
                msg.attach_alternative(content, "text/html")
                msg.send()
                response = {'error_no': "0", 'error_info': "邮件发送成功"}
            else:
                response = {'error_no': "-1",
                            'error_info': "未指定邮件标志位flag，邮件将不会发送。flag=0表示发送课程发布邮件，flag=1表示发送课程取消邮件"}
        except Exception as e:
            response = {'error_no': "-1", 'error_info': "{}".format(e)}
    else:
        response = {'error_no': "-1", 'error_info': "邮件未能正确发送"}
    return HttpResponse(json.dumps(response, cls=DateEncoder), content_type="application/json")


